package com.wangc.report.service.impl;

import com.wangc.report.dao.ConfigMapper;
import com.wangc.report.entity.ConfigEntity;
import com.wangc.report.entity.TaskLogEntity;
import com.wangc.report.service.GenerateService;
import com.wangc.report.service.TaskLogService;
import com.wangc.report.utils.RRException;
import com.wangc.report.utils.ReportCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Service实现类
 *
 * @author wangc
 * @email 1620415297@qq.com
 * @date 2020-10-20 14:13:37
 */
@Service("generateService")
public class GenerateServiceImpl implements GenerateService {
    private static final Logger LOG = LoggerFactory.getLogger(GenerateServiceImpl.class);
    @Resource
    private ConfigMapper configMapper;
    @Autowired
    private ReportCheck reportCheck;
    @Autowired
    private TaskLogService taskLogService;

    @Override
    public void generateReport(String table, String dataDt) {

        ConfigEntity configEntity = configMapper.selectByPrimaryKey(Long.valueOf(table));
        TaskLogEntity taskLogEntity = new TaskLogEntity();
        taskLogEntity.setTableId(configEntity.getTableId());
        taskLogEntity.setDataDt(dataDt);
        taskLogEntity.setTaskName("报表数据生成");
        taskLogEntity.setNewOldFlg("-");
        taskLogEntity.setProcStat("executeing");
        taskLogEntity.setState("0");
        new Thread(() -> {
            try {
                taskLogEntity.setStartDate(new Date());
                taskLogService.save(taskLogEntity);
                reportCheck.generateReport(configEntity.getTableId(), dataDt);
            } catch (Exception e) {
                e.printStackTrace();
                LOG.error(e.toString());
                taskLogEntity.setProcStat("error");
                taskLogEntity.setProcInfo(e.toString());
                taskLogEntity.setFinishDate(new Date());
                taskLogService.update(taskLogEntity);
                throw new RRException(e.toString());
            }
            taskLogEntity.setProcInfo("success");
            taskLogEntity.setProcStat("finish");
            taskLogEntity.setFinishDate(new Date());
            taskLogService.update(taskLogEntity);
        }).start();
    }

}
